//
//  WSQTextView.m
//  WSQTool
//
//  Created by 翁胜琼 on 2018/8/25.
//  Copyright © 2018年 Dev John. All rights reserved.
//  封装 textView

#import "WSQTextView.h"

@interface WSQTextView ()
{
    BOOL _isTyping; // 输入框是否有值
}

@end

@implementation WSQTextView


- (void)awakeFromNib
{
    [super awakeFromNib];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textDidChangeNotic:) name:UITextViewTextDidChangeNotification object:nil];
    
    [self addObserver:self forKeyPath:@"text" options:NSKeyValueObservingOptionNew context:nil];
}

- (instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame])
    {
        // KVO 和通知
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textDidChangeNotic:) name:UITextViewTextDidChangeNotification object:nil];
        
        [self addObserver:self forKeyPath:@"text" options:NSKeyValueObservingOptionNew context:nil];
    }
    return self;
}

- (void)textDidChangeNotic:(NSNotification *)notic
{
    _isTyping = self.text.length != 0;
    
    [self setNeedsDisplay];
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context
{
    if(object == self && [keyPath isEqualToString:@"text"])
    {
        [self textDidChangeNotic:nil];
    }
}

- (void)drawRect:(CGRect)rect {
    // Drawing code
    UIGraphicsGetCurrentContext();    // 获取当前上下文
    
    if (self.placeholder == nil || _isTyping)
    {
        return ;
    }
    
    CGFloat newRectX = rect.origin.x + self.contentInset.left + 4;
    CGFloat newRectY = rect.origin.y + self.contentInset.top + 7;
    CGFloat newRectW = rect.size.width - self.contentInset.left - self.contentInset.right;
    CGFloat newRectH = rect.size.height - self.contentInset.top - self.contentInset.bottom;
    
    CGRect placeholderRect = CGRectMake(newRectX, newRectY, newRectW, newRectH);
    
    UIColor *placeholderColor = self.placeholderColor != nil ? self.placeholderColor : [UIColor grayColor];
    UIFont *placeholderFont = self.placeholderFont == nil ? [UIFont fontWithName:@"PingFang SC" size:13] : self.placeholderFont;
    NSDictionary *attributes = @{
                                 NSForegroundColorAttributeName : placeholderColor,
                                 NSFontAttributeName : placeholderFont
                                 };
    
    [self.placeholder drawInRect:placeholderRect withAttributes:attributes];
    
}

- (void)setPlaceholder:(NSString *)placeholder
{
    _placeholder = placeholder;
    [self setNeedsDisplay];
}

- (void)setPlaceholderColor:(UIColor *)placeholderColor
{
    _placeholderColor = placeholderColor;
    [self setNeedsDisplay];
}

- (void)setPlaceholderFont:(UIFont *)placeholderFont
{
    _placeholderFont = placeholderFont;
    [self setNeedsDisplay];
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

@end
